package org.codeasy.site.devtools.pdm2devfiles.service;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.codeasy.site.devtools.pdm2devfiles.vo.Field;
import org.codeasy.site.devtools.pdm2devfiles.vo.Table;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/*
 * Copyright 1999-2004 Alibaba.com All right reserved. This software is the confidential and proprietary information of
 * Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with Alibaba.com.
 */
/**
 * 类DOM4J.java的实现描述：DOM4J
 * 
 * @author chongan.wangca 2011-9-4 下午04:16:08
 */
public class PDM2DevFiles {

    private static void parse(String fileName) throws Exception {
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(new File(fileName));

        Element rootElement = document.getRootElement();
        List<Element> tableElementsList = queryElementsForList("Table", "Id", rootElement);
        List<Table> tablesList = new ArrayList<Table>();
        for (int i = 0; i < tableElementsList.size(); i++) {

            Element tableElement = tableElementsList.get(i);
            Table table = new Table();
            table.setName(getElementText("Name", tableElement));
            table.setCode(getElementText("Code", tableElement));
            table.setCreationDate(longValueOf(getElementText("CreationDate", tableElement)));
            table.setCreator(getElementText("Creator", tableElement));
            table.setModificationDate(longValueOf(getElementText("ModificationDate", tableElement)));
            table.setModifier(getElementText("Modifier", tableElement));
            table.setComment(getElementText("Comment", tableElement));

            List<Element> columnElementsList = queryElementsForList("Column", "Id", tableElement);

            for (int j = 0; j < columnElementsList.size(); j++) {
                Element columnElement = columnElementsList.get(j);
                Field field = new Field();
                field.setName(getElementText("Name", columnElement));
                field.setCode(getElementText("Code", columnElement));
                field.setCreationDate(longValueOf(getElementText("CreationDate", columnElement)));
                field.setCreator(getElementText("Creator", columnElement));
                field.setModificationDate(longValueOf(getElementText("ModificationDate", columnElement)));
                field.setModifier(getElementText("Modifier", columnElement));
                field.setComment(getElementText("Comment", columnElement));
                field.setDataType(getElementText("DataType", columnElement));
                field.setLength(longValueOf(getElementText("Length", columnElement)));
                table.addField(field);
            }

            tablesList.add(table);
        }

        for (int k = 0; k < tablesList.size(); k++) {
            Table table = tablesList.get(k);
            log(table.getName(), table.getCode(), table.getCreationDate(), table.getCreator(),
                table.getModificationDate(), table.getModifier(), table.getComment());
            for (int m = 0; m < table.getFieldsList().size(); m++) {
                Field field = table.getFieldsList().get(m);
                log(field.getName(), field.getCode(), field.getCreationDate(), field.getCreator(),
                    field.getModificationDate(), field.getModifier(), field.getDataType(), field.getLength(),
                    field.getComment());
            }
        }
    }

    public static String getElementText(String elementName, Element rootElement) {
        Element element = queryElement(elementName, 0, rootElement);
        return element != null ? element.getText() : null;
    }

    /**
     * @param elementName
     * @param pos
     * @param element
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Element queryElement(String elementName, int pos, Element element) {
        Iterator<Element> it = element.elementIterator();
        Element myElement = null;
        int cp = -1;
        while (it.hasNext()) {
            myElement = it.next();
            if (elementName.equals(myElement.getName()) && ++cp == pos) {
                return myElement;
            } else {
                Element oElement = queryElement(elementName, pos, myElement);
                if (oElement != null) {
                    return oElement;
                }
            }
        }
        return null;
    }

    /**
     * @param elementName
     * @param attributeName
     * @param attrbuteValue
     * @param element
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Element queryElement(String elementName, String attributeName, String attrbuteValue, Element element) {
        Iterator<Element> it = element.elementIterator();
        Element myElement = null;
        while (it.hasNext()) {
            myElement = it.next();
            if (elementName.equals(myElement.getName()) && myElement.attributeValue(attributeName) != null
                && attrbuteValue.equals(myElement.attributeValue(attributeName))) {
                return myElement;
            } else {
                Element oElement = queryElement(elementName, attributeName, attrbuteValue, myElement);
                if (oElement != null) {
                    return oElement;
                }
            }
        }
        return null;
    }

    /**
     * @param elementName
     * @param attributeName
     * @param element
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Element queryElement(String elementName, String attributeName, Element element) {
        Iterator<Element> it = element.elementIterator();
        Element myElement = null;
        while (it.hasNext()) {
            myElement = it.next();
            if (elementName.equals(myElement.getName()) && myElement.attributeValue(attributeName) != null) {
                return myElement;
            } else {
                Element oElement = queryElement(elementName, attributeName, myElement);
                if (oElement != null) {
                    return oElement;
                }
            }
        }
        return null;
    }

    /**
     * @param elementName
     * @param attributeName
     * @param element
     * @return
     */
    @SuppressWarnings("unchecked")
    public static List<Element> queryElementsForList(String elementName, String attributeName, Element element) {
        Iterator<Element> it = element.elementIterator();
        List<Element> elementsList = new ArrayList<Element>();
        Element myElement = null;
        while (it.hasNext()) {
            myElement = it.next();
            if (elementName.equals(myElement.getName()) && myElement.attributeValue(attributeName) != null) {
                elementsList.add(myElement);
            } else {
                List<Element> oElementList = queryElementsForList(elementName, attributeName, myElement);
                if (oElementList != null && oElementList.size() > 0) {
                    elementsList.addAll(oElementList);
                }
            }
        }
        return elementsList;
    }

    public static void main(String[] args) throws Exception {
        String fileName = "e:/物理数据模型-无名良品-物流项目.xml";
        PDM2DevFiles.parse(fileName);
    }

    public static void log(Object... logs) {
        for (Object log : logs) {
            System.out.print(log + " ——> ");
        }
        System.out.println();
    }

    public static Long longValueOf(String value) {
        if (value != null) {
            try {
                Long.valueOf(value);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
